package com.example.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.comment.dao.APCommentDao;
import com.example.comment.dao.APCommentLikeDao;
import com.example.comment.service.APCommentService;
import com.usian.model.comment.dtos.ApCommentDto;
import com.usian.model.comment.dtos.ApCommentLikeDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * impl apcomment服务
 *
 */
@Service
@Slf4j
public class APCommentServiceImpl implements APCommentService {
    @Autowired
    APCommentDao apCommentDao;
    @Autowired
    APCommentLikeDao apCommentLikeDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Override
    public ResponseResult addComment(ApCommentDto apCommentDto) {
        //参数校验
        if (apCommentDto == null || apCommentDto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String userId = String.valueOf(apCommentDto.getUserId());
        log.info("========>>userId:{}", userId);
        //判断Redis中的key是否存在
        Boolean flag = stringRedisTemplate.hasKey(userId);
        if (flag) {
            String userJson = stringRedisTemplate.opsForValue().get(userId);
            
            ApUser apUser = JSON.parseObject(userJson, ApUser.class);
            log.info("========>>apUser:{}", apUser);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            ApComment apComment = new ApComment();
            apComment.setContent(apCommentDto.getContent());
            apComment.setLikes(0);
            apComment.setCreateTime(new Date());
            
            apCommentDao.insert(apComment);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        
        return ResponseResult.okResult("成功");
    }
    
    /**
     * 点赞操作
     *
     * @param apCommentLikeDto
     * @return {@code ResponseResult}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult like(ApCommentLikeDto apCommentLikeDto) {
        //参数校验
        if (apCommentLikeDto == null || apCommentLikeDto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String userId = String.valueOf(apCommentLikeDto.getUserId());
        log.info("========>>userId:{}", userId);
        //判断Redis中的key是否存在
        Boolean flag = stringRedisTemplate.hasKey(userId);
        if (flag) {
            String userJson = stringRedisTemplate.opsForValue().get(userId);
            
            ApUser apUser = JSON.parseObject(userJson, ApUser.class);
            log.info("========>>apUser:{}", apUser);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            
            if (apCommentLikeDto.getOperation() == 1) {
                //点赞
                Optional<ApComment> optional = apCommentDao.findById(apCommentLikeDto.getCommentId());
                if (optional.isPresent()) {
                    ApComment apComment = optional.get();
                    //新的点赞数
                    apComment.setLikes(apComment.getLikes() + 1);
                    //保存新的点赞数
                    apCommentDao.save(apComment);
                    //保存关联信息
                    ApCommentLike apCommentLike = new ApCommentLike();
                    BeanUtils.copyProperties(apCommentLikeDto, apCommentLike);
                    apCommentLike.setCreateTime(new Date());
                    apCommentLike.setUpdateTime(apCommentLike.getCreateTime());
                    apCommentLikeDao.insert(apCommentLike);
                }
            } else if (apCommentLikeDto.getOperation() == 0) {
                //取消点赞
                Optional<ApComment> optional = apCommentDao.findById(apCommentLikeDto.getCommentId());
                if (optional.isPresent()) {
                    ApComment apComment = optional.get();
                    //新的点赞数
                    Integer likes = apComment.getLikes();
                    apComment.setLikes(likes <= 0 ? 0 : likes - 1);
                    //保存新的点赞数
                    apCommentDao.save(apComment);
                    //保存关联信息
                    ApCommentLike apCommentLike = new ApCommentLike();
                    apCommentLike.setUserId(apCommentLikeDto.getUserId());
                    apCommentLike.setCommentId(apCommentLikeDto.getCommentId());
                    Example example=Example.of(apCommentLike);
                    List apCommentLikeList = apCommentLikeDao.findAll(example);
                    log.info("======>查询到的关联数据的集合{}",apCommentLikeList);
                    //判断集合中是否有数据
                    if (!CollectionUtils.isEmpty(apCommentLikeList)){
                        apCommentLikeDao.deleteAll(apCommentLikeList);
                    }
                  
                }
                
            }
            
        }
        
        return ResponseResult.okResult("");
    }
}
